import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { ACCESS_TOKEN } from '@/util/constants'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/','/user/login', '/user/register', '/user/register-result','/user/alteration','/oa-callback','/oaPhoneLogin'] // no redirect whitelist
const main_tab_arr = ['test','chat','contact','myHome']

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  let docTitle = '移动OA'
  if (to.meta.title) {
    docTitle = to.meta.title
  }

  console.log('from.path',from.path)
  console.log('to.path',to.path)
  //
  // if (to.path === '/oa-callback'){
  //   next()
  //   NProgress.done()
	// return
  // }

  if (Vue.ls.get(ACCESS_TOKEN)) {
    if(!store.getters.pageActive){
      // router.$addRoutes(getDynamicRoute())
    }
    if (to.path === '/') {
      next({name: 'main'})
      //next()
    } else if(to.path==='/logout'){
        store.dispatch('Logout').then(() => {
            window.location.reload()
        })
    }else{
      next()
    }
  } else {

    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      docTitle = '登录'
      next({ path: '/', query: { redirect: to.fullPath } })
    }
  }
  if(to.path=='/'){
    store.commit('SET_PAGE_ACTIVE','main')
  }else{
    let a = main_tab_arr.filter(item=>{
      return to.path.indexOf(item)>=0
    })
    if(a && a.length==1){
      store.commit('SET_PAGE_ACTIVE',a[0])
    }
  }
  document.title = docTitle
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
